const Utils = ecodeSDK.imp(Utils)
const GField = ecodeSDK.imp(GField)
const GEvent = ecodeSDK.imp(GEvent)

const limitDataRange = (src, target) => {
    const form = Utils.getForm()
    const _limit = (tid, s) => {
        const selectids = /field\d/.test(sid) ? form.getFieldValue(s) || '-1' : s
        form.appendBrowserDataUrlParam(tid, {selectids})
    }
    const sfm = GField.getFieldInfo(src)
    const tfm = GField.getFieldInfo(target)
    if (!sfm.isDetail && !tfm.isDetail) {
        // src: 主表，target：主表
        _limit(tfm.fieldId, sfm.fieldId)
    }
    if (!sfm.isDetail && tfm.isDetail) {
        // src: 主表，target：明细表
        form.registerAction(form.ACTION_ADDROW + tfm.detailId,
            idx => _limit(`${tfm}_${idx}`, sfm.fieldId))
    }
    if (sfm.isDetail && !tfm.isDetail) {
        // src: 明细表，target：主表
        GEvent.bindFieldChangeEvent(sfm.fieldId, () => {
            const arr = GField.getFieldValue(sfm.fieldId).split(',')
            const str = window._.union(arr).join(',')
            _limit(tfm.fieldId, str)
        })
    }
    if (sfm.isDetail && tfm.isDetail) {
        // src: 明细表, target: 明细表
        form.registerAction(form.ACTION_ADDROW + tfm.detailId, idx => {
            const arr = GField.getFieldValue(sfm.fieldId).split(',')
            const str = window._.union(arr).join(',')
            _limit(`${tfm.fieldId}_${idx}`, str)
        })
    }
}

window.GForm = {
    ...Utils,
    ...GField,
    ...GEvent,
	limitDataRange,
	VERSION: '1.0.0'
}